# -*- coding: utf-8 -*-
from odoo import api, fields, models, _, tools
from odoo.osv import expression
from odoo.exceptions import UserError, ValidationError
from .. import public

class AccountAccountType(models.Model):
    _name = "cncw.account.type"
    _description = "科目类型"

    name = fields.Char(string=u'科目类型', required=True, translate=False)
    note = fields.Char(string=u'备注')
    include_initial_balance = fields.Boolean(string=u"账户余额结转",)
    type = fields.Selection([
        ('other', u'固定规则'),
        ('receivable', u'应收账款'),
        ('payable', u'应付账款'),
        ('liquidity', u'流动资产'),
    ], required=True, default='other',)
    internal_group = fields.Selection([
        ('equity', '相等'),
        ('asset', u'资产'),
        ('liability', u'流动资产'),
        ('income', u'收入'),
        ('expense', u'费用'),
        ('off_balance', u'不平'),
    ], string=u"内部分类",
        required=True,)

    @api.model
    def create(self, values):
        if 'name' in values:
            if values['name']:
                public.check_unique(self, ['name'], values, u'科目类型')
        res_id = super(AccountAccountType, self).create(values)
        return res_id

    def write(self, vals, ):
        if 'name' in vals:
            public.check_unique(self, ['name'], vals, u'科目类型')
        res = super(AccountAccountType, self).write(vals)
        return res


class AccountAccount(models.Model):
    _name = "cncw.account"
    _description = "会计科目"
    _check_company_auto = True
    _order = "company_id,parent_left"
    _parent_store = True
    _rec_name = 'code'

    @api.depends('code', 'complete_name')
    def name_get(self):
        res = []
        for record in self:
            name = '%s' % (record.complete_name)
            # name=record.code
            res.append((record['id'], name))
        return res

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        args = args or []
        recs = self.browse()
        if name:
            recs = self.search(
                ['|', '|', '|', ('name', operator, name), '&', ('code', 'like', name), ('code', '>=', name),
                 ('short_code', operator, name), ('complete_name', operator, name)] + args,
                limit=limit)
        if not recs:
            recs = self.search([('name', operator, name)] + args, limit=limit)
        return recs.name_get()

    @api.model
    def get_sub_account_ids(self, account_id=False):
        """
        由会科取其 可用 辅助核算
        :param self:
        :param account_id:
        :return:
        """
        subaccounts = self.env['res.partner'].browse([])
        # 增加判断是否有多辅助核算的数据，没有的话沿用原来的逻辑
        if account_id and account_id.subaccount_category_ids:
            for subaccount_category_id in account_id.subaccount_category_ids:
                if subaccount_category_id.code == 'customer':
                    subaccounts = self.env['res.partner'].search([('customer_rank', '>', 0)])
                elif subaccount_category_id.code == 'supplier':
                    subaccounts = self.env['res.partner'].search([('supplier_rank', '>', 0)])
                else:
                    for x in subaccount_category_id.sub_account_ids:
                        subaccounts |= x
        elif account_id and account_id.subaccount_category_id:
            if account_id.subaccount_category_id.code == 'customer':
                subaccounts = self.env['res.partner'].search([('customer_rank', '>', 0)])
            elif account_id.subaccount_category_id.code == 'supplier':
                subaccounts = self.env['res.partner'].search([('supplier_rank', '>', 0)])
            else:
                for x in account_id.subaccount_category_id.sub_account_ids:
                    subaccounts |= x
        return subaccounts

    def update_level(self):
        objs = self.env['cncw.account'].search([('active', '=', True)])
        for obj in objs:
            obj._get_level()

    @api.depends('parent_id')
    def _get_level(self):
        level = 1
        parent = self.parent_id
        while parent:
            level += 1
            parent = parent.parent_id
        self.level = level

    @api.depends('parent_id', 'code', 'name')
    def _compute_complete_code(self):
        for record in self:
            name = ""
            code = ""
            if record.parent_id:
                # code = (self.parent_id and self.parent_id.complete_code or '')
                name = (record.parent_id and record.parent_id.complete_name or '')
            # code += (self.code and self.code or '')
            name += (record.name and record.name or '')
            record.complete_name = name

    @api.depends('children_ids', 'parent_id')
    def complete_has_children(self):
        for record in self:
            if record.parent_id and not record.parent_id.has_children:
                record.parent_id.has_children = True
            if len(record.children_ids) > 0:
                record.has_children = True
            else:
                record.has_children = False

    @api.constrains('internal_type', 'reconcile')
    def _check_reconcile(self):
        for account in self:
            if account.internal_type in ('receivable', 'payable') and account.reconcile == False:
                raise ValidationError((u'您不能有无法对账的应收账款/应付账款,其编码是 : %s)', account.code))

    cncw_org = fields.Many2one('cncw.org', u'核算机构', ondelete='cascade',)
    code = fields.Char(u'科目编码',size=64, required=True, index=True)
    has_children = fields.Boolean(u'有子阶', default=False, compute="complete_has_children")
    name = fields.Char(u'科目名称', required=True)
    complete_name = fields.Char(compute='_compute_complete_code', store=True, string=u'全称')
    parent_id = fields.Many2one('cncw.account', u'上级科目', ondelete='cascade', domain=[('type', '=', 'view')])
    children_ids = fields.One2many('cncw.account', 'parent_id', u'明细科目')
    user_type_id = fields.Many2one('cncw.account.type', string='Type', required=False,)
    sub_account_type = fields.Selection(public.SUB_ACCOUNT_TYPE, u'会科属性', required=True, default='none')
    subaccount_category_id = fields.Many2one('subaccount.category', u'辅助核算类别', required=False,
                                             ondelete="restrict")
    subaccount_category_ids = fields.Many2many('subaccount.category', string=u'辅助核算类别')
    dc_type = fields.Selection(public.DC_TYPE, u'借贷', default='D')
    dc_type_int = fields.Integer(u'借贷值', help=u'用于计算', compute='compute_dc_type', store=True)
    active = fields.Boolean(u'启用', default=True)
    parent_left = fields.Integer(u'Parent Left', default=0)
    parent_right = fields.Integer(u'Parent Right', default=0)
    parent_path = fields.Char(index=True)
    level = fields.Integer(u'阶层', compute='_get_level', store=True, default=1)
    account_category = fields.Selection([('1', u'资产类'),
                                         ('2', u'负债类'),
                                         ('3', u'共同类'),
                                         ('4', u'所有者权益类'),
                                         ('5', u'成本类'),
                                         ('6', u'费用类'),
                                         ('7', u'收入类'),
                                         ], u'科目大类', default='1')

    ap_ar_type = fields.Selection([('10', u'预付帐款'),
                                   ('11', u'应付帐款'),
                                   ('12', u'应付费用'),
                                   ('13', u'其它应付'),
                                   ('20', u'预收帐款'),
                                   ('21', u'应收帐款'),

                                   ('23', u'其它应收'), ], u'应付应收科目类别', help=u'用于ap ar 月结时金额规类汇总')
    currency_id = fields.Many2one('res.currency', u'币别', default=lambda self: self.env.user.company_id.currency_id)
    short_code = fields.Char(u'简码')
    active =  fields.Boolean(u'启用', default=True)
    deprecated = fields.Boolean(index=True, default=False)
    used = fields.Boolean(compute='_compute_used', search='_search_used')

    internal_type = fields.Selection(related='user_type_id.type', string=u"内部分类", store=True, readonly=True)
    internal_group = fields.Selection(related='user_type_id.internal_group', string=u"内部分类", store=True, readonly=True)
    #has_unreconciled_entries = fields.Boolean(compute='_compute_has_unreconciled_entries',
    #    help="The account has at least one unreconciled debit and credit since last time the invoices & payments matching was performed.")
    reconcile = fields.Boolean(string='允许对帐', default=False,)
    note = fields.Text(u'备注')
    company_id = fields.Many2one('res.company', string=u'公司', required=True, readonly=True,
        default=lambda self: self.env.company)
    root_id = fields.Many2one('cncw.root', compute='_compute_account_root', store=True)

    @api.depends('code')
    def _compute_account_root(self):
        # this computes the first 2 digits of the account.
        # This field should have been a char, but the aim is to use it in a side panel view with hierarchy, and it's only supported by many2one fields so far.
        # So instead, we make it a many2one to a psql view with what we need as records.
        for record in self:
            record.root_id = (ord(record.code[0]) * 1000 + ord(record.code[1:2] or '\x00')) if record.code else False


    _sql_constraints = [
        ('code_company_uniq', 'unique (code,company_id)', u'每个公司编码必须唯一 !')
    ]

    def get_subaccount_category_ids(self):
        res = self.env['subaccount.category']
        for record in self:
            if record.sub_account_type == 'has':
                res |= record.subaccount_category_ids
        return res

    def init(self):
        self._cr.execute("""
            update cncw_account set parent_left=0 where parent_left is null;
            update cncw_account set parent_right=0 where parent_left is null;
        """)

    def write(self, vals, ):
        if 'active' in vals:
            vals.update(dict(deprecated=vals.get('active', False)))
        res = super(AccountAccount, self).write(vals)
        return res

    @api.onchange('name')
    def onchange_name(self):
        if self.name:
            self.short_code = public.multi_get_letter(self, self.name)
        else:
            self.short_code = ''

    @api.depends('dc_type')
    def compute_dc_type(self):
        for record in self:
            if record.dc_type == 'D':
                record.dc_type_int = 1
            else:
                record.dc_type_int = -1

    # @api.constrains('reconcile', 'internal_group', 'tax_ids')
    # def _constrains_reconcile(self):
    #     for record in self:
    #         if record.internal_group == 'off_balance':
    #             if record.reconcile:
    #                 raise UserError(_('An Off-Balance account can not be reconcilable'))
    #             if record.tax_ids:
    #                 raise UserError(_('An Off-Balance account can not have taxes'))
    #
    # @api.constrains('allowed_journal_ids')
    # def _constrains_allowed_journal_ids(self):
    #     self.env['cncw.move.line'].flush(['account_id', 'journal_id'])
    #     self.flush(['allowed_journal_ids'])
    #     self._cr.execute("""
    #         SELECT aml.id
    #         FROM cncw_move_line aml
    #         WHERE aml.account_id in %s
    #         AND EXISTS (SELECT 1 FROM cncw_account_account_journal_rel WHERE cncw_account_id = aml.account_id)
    #         AND NOT EXISTS (SELECT 1 FROM cncw_account_account_journal_rel WHERE cncw_account_id = aml.account_id AND account_journal_id = aml.journal_id)
    #     """, [tuple(self.ids)])
    #     ids = self._cr.fetchall()
    #     if ids:
    #         raise ValidationError(_('Some journal items already exist with this account but in other journals than the allowed ones.'))
    #
    # @api.constrains('currency_id')
    # def _check_journal_consistency(self):
    #     ''' Ensure the currency set on the journal is the same as the currency set on the
    #     linked accounts.
    #     '''
    #     if not self:
    #         return
    #
    #     self.env['cncw.account'].flush(['currency_id'])
    #     self.env['cncw.account.journal'].flush([
    #         'currency_id',
    #         'default_account_id',
    #         'payment_debit_account_id',
    #         'payment_credit_account_id',
    #         'suspense_account_id',
    #     ])
    #     self._cr.execute('''
    #         SELECT account.id, journal.id
    #         FROM cncw_account account
    #         JOIN res_company company ON company.id = account.company_id
    #         JOIN account_journal journal ON
    #             journal.default_account_id = account.id
    #         WHERE account.id IN %s
    #         AND journal.type IN ('bank', 'cash')
    #         AND journal.currency_id IS NOT NULL
    #         AND journal.currency_id != company.currency_id
    #         AND account.currency_id != journal.currency_id
    #     ''', [tuple(self.ids)])
    #     res = self._cr.fetchone()
    #     if res:
    #         account = self.env['cncw.account'].browse(res[0])
    #         journal = self.env['cncw.account.journal'].browse(res[1])
    #         raise ValidationError(_(
    #             "The foreign currency set on the journal '%(journal)s' and the account '%(account)s' must be the same.",
    #             journal=journal.display_name,
    #             account=account.display_name
    #         ))
    #
    # @api.constrains('company_id')
    # def _check_company_consistency(self):
    #     if not self:
    #         return
    #
    #     self.flush(['company_id'])
    #     self._cr.execute('''
    #         SELECT line.id
    #         FROM cncw_move_line line
    #         JOIN cncw_account account ON account.id = line.account_id
    #         WHERE line.account_id IN %s
    #         AND line.company_id != account.company_id
    #     ''', [tuple(self.ids)])
    #     if self._cr.fetchone():
    #         raise UserError(_("You can't change the company of your account since there are some journal items linked to it."))

    # @api.constrains('user_type_id')
    # def _check_user_type_id_sales_purchase_journal(self):
    #     if not self:
    #         return
    #
    #     self.flush(['user_type_id'])
    #     self._cr.execute('''
    #         SELECT account.id
    #         FROM cncw_account account
    #         JOIN cncw_account_type acc_type ON account.user_type_id = acc_type.id
    #         JOIN account_journal journal ON journal.default_account_id = account.id
    #         WHERE account.id IN %s
    #         AND acc_type.type IN ('receivable', 'payable')
    #         AND journal.type IN ('sale', 'purchase')
    #         LIMIT 1;
    #     ''', [tuple(self.ids)])
    #
    #     if self._cr.fetchone():
    #         raise ValidationError(_("The account is already in use in a 'sale' or 'purchase' journal. This means that the account's type couldn't be 'receivable' or 'payable'."))

    # @api.constrains('reconcile')
    # def _check_used_as_journal_default_debit_credit_account(self):
    #     accounts = self.filtered(lambda a: not a.reconcile)
    #     if not accounts:
    #         return
    #
    #     self.flush(['reconcile'])
    #     self._cr.execute('''
    #         SELECT journal.id
    #         FROM account_journal journal
    #         WHERE journal.payment_credit_account_id in %(credit_account)s
    #         OR journal.payment_debit_account_id in %(debit_account)s ;
    #     ''', {
    #         'credit_account': tuple(accounts.ids),
    #         'debit_account': tuple(accounts.ids)
    #     })
    #
    #     rows = self._cr.fetchall()
    #     if rows:
    #         journals = self.env['cncw.account.journal'].browse([r[0] for r in rows])
    #         raise ValidationError(_(
    #             "This account is configured in %(journal_names)s journal(s) (ids %(journal_ids)s) as payment debit or credit account. This means that this account's type should be reconcilable.",
    #             journal_names=journals.mapped('display_name'),
    #             journal_ids=journals.ids
    #         ))


    # @api.depends('code')
    # def _compute_account_group(self):
    #     if self.ids:
    #         self.env['account.group']._adapt_accounts_for_account_groups(self)
    #     else:
    #         self.group_id = False

    def _search_used(self, operator, value):
        if operator not in ['=', '!='] or not isinstance(value, bool):
            raise UserError(_('Operation not supported'))
        if operator != '=':
            value = not value
        self._cr.execute("""
            SELECT id FROM cncw_account account
            WHERE EXISTS (SELECT * FROM cncw_move_line aml WHERE aml.account_id = account.id LIMIT 1)
        """)
        return [('id', 'in' if value else 'not in', [r[0] for r in self._cr.fetchall()])]

    def _compute_used(self):
        ids = set(self._search_used('=', True)[0][2])
        for record in self:
            record.used = record.id in ids

    @api.model
    def _search_new_account_code(self, company, digits, prefix):
        for num in range(1, 10000):
            new_code = str(prefix.ljust(digits - 1, '0')) + str(num)
            rec = self.search([('code', '=', new_code), ('company_id', '=', company.id)], limit=1)
            if not rec:
                return new_code
        raise UserError(_('Cannot generate an unused account code.'))

    # def _compute_opening_debit_credit(self):
    #     self.opening_debit = 0
    #     self.opening_credit = 0
    #     self.opening_balance = 0
    #     if not self.ids:
    #         return
    #     self.env.cr.execute("""
    #         SELECT line.account_id,
    #                SUM(line.balance) AS balance,
    #                SUM(line.debit) AS debit,
    #                SUM(line.credit) AS credit
    #           FROM cncw_move_line line
    #           JOIN res_company comp ON comp.id = line.company_id
    #          WHERE line.move_id = comp.account_opening_move_id
    #            AND line.account_id IN %s
    #          GROUP BY line.account_id
    #     """, [tuple(self.ids)])
    #     result = {r['account_id']: r for r in self.env.cr.dictfetchall()}
    #     for record in self:
    #         res = result.get(record.id) or {'debit': 0, 'credit': 0, 'balance': 0}
    #         record.opening_debit = res['debit']
    #         record.opening_credit = res['credit']
    #         record.opening_balance = res['balance']

    @api.depends('internal_group')
    def _compute_is_off_balance(self):
        for account in self:
            account.is_off_balance = account.internal_group == "off_balance"

    def _set_opening_debit(self):
        for record in self:
            record._set_opening_debit_credit(record.opening_debit, 'debit')

    def _set_opening_credit(self):
        for record in self:
            record._set_opening_debit_credit(record.opening_credit, 'credit')

    # def _set_opening_debit_credit(self, amount, field):
    #     """ Generic function called by both opening_debit and opening_credit's
    #     inverse function. 'Amount' parameter is the value to be set, and field
    #     either 'debit' or 'credit', depending on which one of these two fields
    #     got assigned.
    #     """
    #     self.company_id.create_op_move_if_non_existant()
    #     opening_move = self.company_id.account_opening_move_id
    #
    #     if opening_move.state == 'draft':
    #         # check whether we should create a new move line or modify an existing one
    #         account_op_lines = self.env['cncw.move.line'].search([('account_id', '=', self.id),
    #                                                                   ('move_id','=', opening_move.id),
    #                                                                   (field,'!=', False),
    #                                                                   (field,'!=', 0.0)]) # 0.0 condition important for import
    #
    #         if account_op_lines:
    #             op_aml_debit = sum(account_op_lines.mapped('debit'))
    #             op_aml_credit = sum(account_op_lines.mapped('credit'))
    #
    #             # There might be more than one line on this account if the opening entry was manually edited
    #             # If so, we need to merge all those lines into one before modifying its balance
    #             opening_move_line = account_op_lines[0]
    #             if len(account_op_lines) > 1:
    #                 merge_write_cmd = [(1, opening_move_line.id, {'debit': op_aml_debit, 'credit': op_aml_credit, 'partner_id': None ,'name': _("Opening balance")})]
    #                 unlink_write_cmd = [(2, line.id) for line in account_op_lines[1:]]
    #                 opening_move.write({'line_ids': merge_write_cmd + unlink_write_cmd})
    #
    #             if amount:
    #                 # modify the line
    #                 opening_move_line.with_context(check_move_validity=False)[field] = amount
    #             else:
    #                 # delete the line (no need to keep a line with value = 0)
    #                 opening_move_line.with_context(check_move_validity=False).unlink()
    #
    #         elif amount:
    #             # create a new line, as none existed before
    #             self.env['cncw.move.line'].with_context(check_move_validity=False).create({
    #                     'name': _('Opening balance'),
    #                     field: amount,
    #                     'move_id': opening_move.id,
    #                     'account_id': self.id,
    #             })
    #
    #         # Then, we automatically balance the opening move, to make sure it stays valid
    #         if not 'import_file' in self.env.context:
    #             # When importing a file, avoid recomputing the opening move for each account and do it at the end, for better performances
    #             self.company_id._auto_balance_opening_move()

    @api.model
    def default_get(self, default_fields):
        """If we're creating a new account through a many2one, there are chances that we typed the account code
        instead of its name. In that case, switch both fields values.
        """
        if 'name' not in default_fields and 'code' not in default_fields:
            return super().default_get(default_fields)
        default_name = self._context.get('default_name')
        default_code = self._context.get('default_code')
        if default_name and not default_code:
            try:
                default_code = int(default_name)
            except ValueError:
                pass
            if default_code:
                default_name = False
        contextual_self = self.with_context(default_name=default_name, default_code=default_code)
        return super(AccountAccount, contextual_self).default_get(default_fields)

    @api.model
    def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
        args = args or []
        domain = []
        if name:
            domain = ['|', ('code', '=ilike', name.split(' ')[0] + '%'), ('name', operator, name)]
            if operator in expression.NEGATIVE_TERM_OPERATORS:
                domain = ['&', '!'] + domain[1:]
        return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)

    @api.onchange('user_type_id')
    def _onchange_user_type_id(self):
        self.reconcile = self.internal_type in ('receivable', 'payable')
        if self.internal_type == 'liquidity':
            self.reconcile = False
        elif self.internal_group == 'off_balance':
            self.reconcile = False
            self.tax_ids = False
        elif self.internal_group == 'income' and not self.tax_ids:
            self.tax_ids = self.company_id.account_sale_tax_id
        elif self.internal_group == 'expense' and not self.tax_ids:
            self.tax_ids = self.company_id.account_purchase_tax_id

    def name_get(self):
        result = []
        for account in self:
            name = account.code + ' ' + account.name
            result.append((account.id, name))
        return result

    @api.returns('self', lambda value: value.id)
    def copy(self, default=None):
        default = dict(default or {})
        if default.get('code', False):
            return super(AccountAccount, self).copy(default)
        try:
            default['code'] = (str(int(self.code) + 10) or '').zfill(len(self.code))
            default.setdefault('name', _("%s (copy)") % (self.name or ''))
            while self.env['cncw.account'].search([('code', '=', default['code']),
                                                      ('company_id', '=', default.get('company_id', False) or self.company_id.id)], limit=1):
                default['code'] = (str(int(default['code']) + 10) or '')
                default['name'] = _("%s (copy)") % (self.name or '')
        except ValueError:
            default['code'] = _("%s (copy)") % (self.code or '')
            default['name'] = self.name
        return super(AccountAccount, self).copy(default)

    #
    # def _toggle_reconcile_to_true(self):
    #     '''Toggle the `reconcile´ boolean from False -> True
    #
    #     Note that: lines with debit = credit = amount_currency = 0 are set to `reconciled´ = True
    #     '''
    #     if not self.ids:
    #         return None
    #     query = """
    #         UPDATE cncw_move_line SET
    #             reconciled = CASE WHEN debit = 0 AND credit = 0 AND amount_currency = 0
    #                 THEN true ELSE false END,
    #             amount_residual = (debit-credit),
    #             amount_residual_currency = amount_currency
    #         WHERE full_reconcile_id IS NULL and account_id IN %s
    #     """
    #     self.env.cr.execute(query, [tuple(self.ids)])
    #
    # def _toggle_reconcile_to_false(self):
    #     '''Toggle the `reconcile´ boolean from True -> False
    #
    #     Note that it is disallowed if some lines are partially reconciled.
    #     '''
    #     if not self.ids:
    #         return None
    #     partial_lines_count = self.env['cncw.move.line'].search_count([
    #         ('account_id', 'in', self.ids),
    #         ('full_reconcile_id', '=', False),
    #         ('|'),
    #         ('matched_debit_ids', '!=', False),
    #         ('matched_credit_ids', '!=', False),
    #     ])
    #     if partial_lines_count > 0:
    #         raise UserError(_('You cannot switch an account to prevent the reconciliation '
    #                           'if some partial reconciliations are still pending.'))
    #     query = """
    #         UPDATE cncw_move_line
    #             SET amount_residual = 0, amount_residual_currency = 0
    #         WHERE full_reconcile_id IS NULL AND account_id IN %s
    #     """
    #     self.env.cr.execute(query, [tuple(self.ids)])
    #
    # def write(self, vals):
    #     # Do not allow changing the company_id when cncw_move_line already exist
    #     if vals.get('company_id', False):
    #         move_lines = self.env['cncw.move.line'].search([('account_id', 'in', self.ids)], limit=1)
    #         for account in self:
    #             if (account.company_id.id != vals['company_id']) and move_lines:
    #                 raise UserError(_('You cannot change the owner company of an account that already contains journal items.'))
    #     if 'reconcile' in vals:
    #         if vals['reconcile']:
    #             self.filtered(lambda r: not r.reconcile)._toggle_reconcile_to_true()
    #         else:
    #             self.filtered(lambda r: r.reconcile)._toggle_reconcile_to_false()
    #
    #     if vals.get('currency_id'):
    #         for account in self:
    #             if self.env['cncw.move.line'].search_count([('account_id', '=', account.id), ('currency_id', 'not in', (False, vals['currency_id']))]):
    #                 raise UserError(_('You cannot set a currency on this account as it already has some journal entries having a different foreign currency.'))
    #
    #     return super(AccountAccount, self).write(vals)
    #
    # def unlink(self):
    #     if self.env['cncw.move.line'].search([('account_id', 'in', self.ids)], limit=1):
    #         raise UserError(_('You cannot perform this action on an account that contains journal items.'))
    #     #Checking whether the account is set as a property to any Partner or not
    #     values = ['cncw.account,%s' % (account_id,) for account_id in self.ids]
    #     partner_prop_acc = self.env['ir.property'].sudo().search([('value_reference', 'in', values)], limit=1)
    #     if partner_prop_acc:
    #         account_name = partner_prop_acc.get_by_record().display_name
    #         raise UserError(
    #             ('你不能删除已经设置了的科目%s.', account_name)
    #         )
    #     return super(AccountAccount, self).unlink()

    def action_duplicate_accounts(self):
        for account in self.browse(self.env.context['active_ids']):
            account.copy()

class AccountRoot(models.Model):
    _name = 'cncw.root'
    _description = '基础root'
    _auto = False

    name = fields.Char()
    parent_id = fields.Many2one('cncw.root')
    company_id = fields.Many2one('res.company')

    def init(self):
        tools.drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute('''
            CREATE OR REPLACE VIEW %s AS (
            SELECT DISTINCT ASCII(code) * 1000 + ASCII(SUBSTRING(code,2,1)) AS id,
                   LEFT(code,2) AS name,
                   ASCII(code) AS parent_id,
                   company_id
            FROM cncw_account WHERE code IS NOT NULL
            UNION ALL
            SELECT DISTINCT ASCII(code) AS id,
                   LEFT(code,1) AS name,
                   NULL::int AS parent_id,
                   company_id
            FROM cncw_account WHERE code IS NOT NULL
            )''' % (self._table,)
        )